﻿using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using AlipaySDK.Dto.Auth;
using AlipaySDK.Helper;
using Common.Logging;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.Helpers;

namespace User.Api.Controllers
{
    public class AuthController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(AuthController));
        private static readonly string WxOauth2State = "GbkYin666";

        [AllowAnonymous]
        [HttpGet]
        [ActionName("WxOauth2")]
        public HttpResponseMessage WxOauth2(string url, string auth_code, string state, string app_id,string scope,string source)
        {
            string failedUrl = ConfigurationManager.AppSettings["H5BaseAddress"] + "/index/401";

            if (string.IsNullOrEmpty(auth_code))
            {
                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }

            if (state != WxOauth2State)
            {
                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }

            GetOauth2OpenIdResponse result = null;

            //通过，用code换取access_token
            try
            {
                result = Auth.GetOauth2OpenId(auth_code, app_id);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("服务窗网页授权获取用户信息第一步出错，授权码:{0},信息：{1}", auth_code, JsonConvert.SerializeObject(ex));

                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }
            if (result.ResultCode != "0")
            {
                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }

            GetOauth2UserInfoResponse userInfo = null;
            try
            {
                userInfo = Auth.GetOauth2UserinfoShare(app_id,result.AccessToken);
                // TODO 获取用户信息
                //Logger.InfoFormat("服务窗获取用户信息，信息：{0}", JsonConvert.SerializeObject(userInfo));
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat(result.OpenId+"服务窗网页授权获取用户信息第二步出错，信息：{0}", JsonConvert.SerializeObject(ex));
            }

            long userId = 0;
            var openId = result.OpenId; 

            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                var user = ctx.WxUsers.FirstOrDefault(x => x.OpenId == openId);
                if (user != null)
                {
                    user.RecStatus = 1;
                    user.LastActiveDt = DateTime.Now;
                    user.UnsubscribeDt = null;
                    user.RecUpdateDt = DateTime.Now;
                    user.UserRealName = userInfo?.RealName;
                    user.CertNo = userInfo?.CertNo;
                    user.Mobile = userInfo?.Mobile;
                    user.Gender = userInfo?.Gender;
                }
                else
                {
                    user = new OutDbContext.WxUser
                    {
                        OpenId = openId,
                        SubscribeDt = DateTime.Now,
                        LastActiveDt = DateTime.Now,
                        IsBkMember = 0,
                        RecStatus = 1,
                        RecCreateDt = DateTime.Now,
                        UserType = "AliPay",
                        UserRealName = userInfo?.RealName,
                        CertNo = userInfo?.CertNo,
                        Mobile = userInfo?.Mobile,
                        Gender = userInfo?.Gender
                    };

                    ctx.WxUsers.Add(user);
                }

                ctx.SaveChanges();
                userId = user.Id;
            }

            var response = Request.CreateResponse(HttpStatusCode.Redirect);
            response.Headers.Location = new Uri(url);

            var cookie = new CookieHeaderValue("AzuCookie",
                LocalUserTokenHelper.GenerateLocalToken(userId, openId));
            //cookie.Domain = Request.RequestUri.Host;
            cookie.Path = "/";
            response.Headers.AddCookies(new[] { cookie });

            return response;
        }

        [HttpGet]
        [AllowAnonymous]
        [ActionName("GetWxOauth2Url")]
        public string GetWxOauth2Url(string url)
        {
            var baseAddress = ConfigurationManager.AppSettings["BaseAddress"];
            var appId = ConfigurationManager.AppSettings["WeixinAppId"];

            var redirectUrl = baseAddress + "api/Auth/WxOauth2?url=" + HttpUtility.UrlEncode(url);
            //https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2015052700092241&auth_skip=false&scope=auth_userinfo&state={WxOauth2State}&redirect_uri=http://wx.e3861.com/api/Auth/WxOauth2?url=http://wx.e3861.com/h5/index.html#!/index/get-queue
            var oauth2Url =
                $"https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id={appId}&auth_skip=false&scope=auth_userinfo&state={WxOauth2State}&redirect_uri={HttpUtility.UrlEncode(redirectUrl)}";

            return oauth2Url;
        }

        /// <summary>
        /// 获取oauth2的网页地址
        /// </summary>
        /// <param name="routePath">比如 "/index/portal/"</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [ActionName("GetH5Url")]
        public string GetH5Url(string routePath)
        {
            var h5BaseAddress = ConfigurationManager.AppSettings["H5BaseAddress"];
            var baseAddress = ConfigurationManager.AppSettings["BaseAddress"];
            var appId = ConfigurationManager.AppSettings["WeixinAppId"];

            var url = h5BaseAddress + routePath;
            var redirectUrl = baseAddress + "api/Auth/WxOauth2?url=" + HttpUtility.UrlEncode(url);
            //https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2015052700092241&auth_skip=false&scope=auth_userinfo&state={WxOauth2State}&redirect_uri=http://wx.e3861.com/api/Auth/WxOauth2?url=http://wx.e3861.com/h5/index.html#!/index/get-queue
            var oauth2Url =
                $"https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id={appId}&auth_skip=false&scope=auth_userinfo&state={WxOauth2State}&redirect_uri={HttpUtility.UrlEncode(redirectUrl)}";

            return oauth2Url;
        }
    }
}
